<template>
	<div class="layout-padding fillings-container">
		<HyTable
			:tableConfig="tableConfig"
			:tableColumns="tableColumns"
			:searchConfig="searchConfig"
			:searchFields="searchFields"
			:searchDefault="searchDefault"
			:buttonConfig="buttonConfig"
			ref="hyTableRef"
		>
			<template #tableHeader>
				<el-button @click="showDialogForm" plain icon="Pointer">立即抽检</el-button>
			</template>
			<template #stateSlot="{ row }">
				<el-tag class="start-tag" v-if="row.opinionStatusName == '未填写' || row.opinion_status == 1">{{ row.opinionStatusName }}</el-tag>
				<el-tag class="agree-tag" v-else-if="row.opinionStatusName == '正常' || row.opinion_status == 2">{{ row.opinionStatusName }}</el-tag>
				<el-tag class="refuse-tag" v-else>{{ row.opinionStatusName }}</el-tag>
			</template>
			<template #operation>
				<el-table-column fixed="right" label="操作" width="130">
					<template #default="{ row }">
						<el-button text color="#a593e0" plain icon="Document" @click="showDetail(row)" v-if="row.opinion_status == 1 || !row.opinion_status"
							>填写意见</el-button
						>
						<el-button icon="View" text type="primary" @click="showDetail(row)" v-else>查看</el-button>
					</template>
				</el-table-column>
			</template>
		</HyTable>
		<!-- 填写意见 -->
		<advice-dialog
			v-if="dialogFormOption"
			:hyFormConfig="hyFormOptionConfig"
			:hyFormFields="hyFormOptionFields"
			:hyFormDefault="hyFormOptionDefault"
			:appCode="appCode"
			:declareId="declareId"
			:implementationId="implementationId"
			@handleCancel="closeDialog"
		>
		</advice-dialog>
		<!-- 立即抽检 -->
		<el-dialog v-model="dialogFormVisible" :title="searchConfig.title" width="600" @close="handleCancel">
			<HyForm ref="hyDiaFormRef" :hyFormDefault="hyFormDefault" :hyFormConfig="hyFormConfig" :hyFormFields="hyFormFields">
				<template #custom>
					<el-col :span="24" :offset="0">
						<el-form-item label="预算金额(万元)">
							<el-col :span="11">
								<el-form-item>
									<el-input-number :controls="false" v-model="custFormData.beginTotalBudget" @blur="blurFirst" :min="0" />
								</el-form-item>
							</el-col>
							<el-col class="text-center" :span="2">
								<span class="text-gray-500">-</span>
							</el-col>
							<el-col :span="11">
								<el-form-item>
									<el-input-number :controls="false" :min="custFormData.beginTotalBudget" v-model="custFormData.endTotalBudget" />
								</el-form-item>
							</el-col>
						</el-form-item>
					</el-col>
				</template>
			</HyForm>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="handleCancel">取消</el-button>
					<el-button type="primary" @click="confirm"> 确认抽检 </el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue';
import { useRouter } from 'vue-router';
import HyTable from '/@/components/HyTable/components/TableLayout/default.vue';
// import HyTable from '/@/components/HyTable/index.vue';
import HyForm from '/@/components/HyForm/index.vue';
import AdviceDialog from '../components/adviceDialog.vue';
import { spotList } from '/@/api/acceptance';
import { Session } from '/@/utils/storage';
import { useDict } from '/@/hooks/dict';

export default defineComponent({
	name: 'insepation',
	components: {
		HyTable,
		HyForm,
		AdviceDialog,
	},
	setup() {
		const { belong_domain: APP_DOMAIN, opinion_status: OPTIONSTATUS } = useDict('belong_domain', 'opinion_status');

		const router = useRouter();
		const tableColumns = computed(() => {
			return [
				{ prop: 'app_code', label: '数字化应用编号' },
				{ prop: 'app_name', label: '数字化应用名称' },
				{ prop: 'domainName', label: '所属领域' },
				{ prop: 'responsible_dept', label: '责任部门' },
				{ prop: 'create_time', label: '验收时间' },
				{ prop: 'opinionStatusName', label: '状态', slot: 'stateSlot',fixed:'right',width:160 },
			];
		});
		const tableConfig = computed(() => {
			return {
				request: null,
				showSearch: true,
				isCostomTop: false,
				title: '系统抽检',
				defaultData: [],
			};
		});
		const searchConfig = ref({
			labelWidth: '120px',
			span: 6,
			offset: 0,
			type: 'search',
			title: '系统抽检',
			show: false,
		});
		const hyDiaFormRef = ref(null); //弹窗
		const hyTableRef = ref(null); //表格
		function disDate(time) {
			// console.log(time,JSON.parse(JSON.stringify(hyFormDefault.value.timeRange)))
			if (hyDiaFormRef.value?.hyForm) {
				const hyFormSub = initFormData(hyDiaFormRef.value.hyForm);
				if (hyFormSub.timeRange && hyFormSub.timeRange.length > 0) {
					const dateArr = hyFormSub.timeRange.split(',');
					if (time.getTime() < new Date(dateArr[0]).getTime() || time.getTime() > new Date(dateArr[1]).getTime()) {
						return true;
					} else {
						return false;
					}
				} else {
					return false;
				}
			} else {
				if (hyFormDefault.value.timeRange[0]) {
					if (
						time.getTime() < new Date(hyFormDefault.value.timeRange[0]).getTime() ||
						time.getTime() > new Date(hyFormDefault.value.timeRange[1]).getTime()
					) {
						return true;
					} else {
						return false;
					}
				}
				return false;
			}
		}
		// 配置搜索
		const searchFields = ref({
			name: {
				type: 'input',
				label: '关键字',
				span: 8,
				placeholder: '请输入关键字进行模糊搜索',
			},
			status: {
				type: 'select',
				label: '状态',
				span: 8,
				placeholder: '请选择状态',
				options: OPTIONSTATUS,
			},
			timeArr: {
				type: 'date',
				picker: 'datetimerange',
				label: '验收时间',
				span: 8,
				remove: true,
				disabledDate: (time) => disDate(time),
			},
		});
		const buttonConfig = computed(() => {
			return {
				span: 24,
				offset: 20,
			};
		});
		const searchDefault = ref({});
		const dialogFormVisible = ref(false);

		//填写意见
		const dialogFormOption = ref(false);
		const hyFormOptionConfig = computed(() => {
			return {
				span: 24,
				offset: 0,
				labelWidth: '140px',
				type: 'submit',
			};
		});
		const hyFormOptionFields = ref({
			result: {
				type: 'select',
				label: '结果',
				required: true,
				options: [
					{
						label: '正常',
						value: '2',
					},
					{
						label: '异常',
						value: '3',
					},
				],
			},
			opinion: {
				required: true,
				type: 'textarea',
				label: '意见',
			},
		});
		const hyFormOptionDefault = ref({
			result: '',
			opinion: '',
		});
		const appCode = ref('');
		const declareId = ref('');
		const implementationId = ref('');
		function fillOption(row) {
			console.log(row);
			appCode.value = row.app_code;
			declareId.value = row.declare_id;
			implementationId.value = row.implementation_id;
			dialogFormOption.value = true;
		}
		function closeDialog() {
			dialogFormOption.value = false;
		}
		//详情
		function showDetail(row?: any) {
			router.push({
				path: '../detail/acceptance',
				query: {
					id: row.declare_id,
					implementationId: row.implementation_id,
					appCode: row.app_code,
					pageType: 2,
					tagsViewName: '系统抽检详情',
				},
			});
		}
		//立即抽检
		const hyFormConfig = computed(() => {
			return {
				span: 24,
				offset: 0,
				labelWidth: '170px',
				type: 'submit',
			};
		});
		const hyFormFields = ref({
			timeRange: {
				type: 'date',
				label: '按验收日期抽检',
				picker: 'datetimerange',
				required: false,
			},
			beginTotalBudget: {
				required: false,
				type: 'input',
				label: '预算金额(万元)',
				placeholder: '区间起始值',
				remove: true,
			},
			endTotalBudget: {
				required: false,
				type: 'input',
				label: '预算金额(万元)',
				placeholder: '区间结束值',
				remove: true,
			},
			domain: {
				type: 'select',
				label: '所属领域',
				required: false,
				options: APP_DOMAIN,
				change: (e) => {
					console.log(e);
					if (e) {
						const rowArr = APP_DOMAIN.value.filter((item) => item.value == e);
						hyDiaFormRef.value.hyForm.domainName = rowArr.length && rowArr[0].label;
					} else {
						hyDiaFormRef.value.hyForm.domainName = '';
					}
				},
			},
			percentage: {
				type: 'inputNumber',
				label: '抽检应用项目比例(%)',
				required: true,
				max: 100,
				min: 0,
			},
		});
		const hyFormDefault = ref({
			timeRange: [],
			beginTotalBudget: '',
			endTotalBudget: '',
			domain: '',
			domainName: '',
			percentage: null,
		});
		const custFormData = ref({
			beginTotalBudget: null,
			endTotalBudget: null,
		});

		function showDialogForm() {
			dialogFormVisible.value = true;
		}
		function confirm() {
			hyDiaFormRef.value.check().then((valid) => {
				if (valid) {
					console.log(initFormData(hyDiaFormRef.value.hyForm));
					let params = JSON.parse(JSON.stringify(initFormData(hyDiaFormRef.value.hyForm)));
					params['beginTotalBudget'] = custFormData.value.beginTotalBudget;
					params['endTotalBudget'] = custFormData.value.endTotalBudget;
					params['spotBeginTime'] = params.timeRange && params.timeRange.split(',')[0];
					params['spotEndTime'] = params.timeRange && params.timeRange.split(',')[1];
					params['domain'] = params.domain || '';
					delete params.timeRange;
					searchDefault.value = { ...params };
					if (Session.get('insepationObj')) {
						if (params['spotBeginTime']) {
							searchDefault.value['timeArr'] = [params['spotBeginTime'], params['spotEndTime']];
						} else {
							searchDefault.value['timeArr'] = ['1970-01-01:00:00:00', ''];
						}
					}

					Session.set('insepationObj', JSON.stringify({ ...params }));
					tableConfig.value.request = spotList;
					searchFields.value.timeArr.remove = false;
					searchConfig.value.show = true;
					dialogFormVisible.value = false;
					nextTick(() => {
						hyTableRef.value.handleRest();
					});
				}
			});
		}
		function handleCancel() {
			let insepationObj = Session.get('insepationObj');
			if (insepationObj) {
				const params = typeof insepationObj == 'string' ? JSON.parse(insepationObj) : insepationObj;
				custFormData.value.beginTotalBudget = params.beginTotalBudget;
				custFormData.value.endTotalBudget = params.endTotalBudget;
				hyFormDefault.value.percentage = params.percentage;
				hyFormDefault.value.domain = params.domain;
				hyFormDefault.value.domainName = params.domainName;
				hyFormDefault.value.timeRange = [params.spotBeginTime, params.spotEndTime];
				searchDefault.value = params;
			}
			dialogFormVisible.value = false;
		}
		function initFormData(form) {
			form = toRaw(form);
			const obj = {};
			for (const key in form) {
				let val = form[key];
				if (Array.isArray(val)) {
					obj[key] = val.join(',');
				} else {
					obj[key] = val;
				}
			}
			return obj;
		}

		function setOptions(dictionary) {
			const arr = [];
			for (const key in dictionary) {
				arr.push({
					label: dictionary[key],
					value: key,
				});
			}
			return arr;
		}
		function blurFirst(e) {
			if (custFormData.value.endTotalBudget < custFormData.value.beginTotalBudget) {
				custFormData.value.endTotalBudget = custFormData.value.beginTotalBudget;
			}
		}
		onMounted(() => {
			let insepationObj = Session.get('insepationObj');
			if (insepationObj) {
				const params = typeof insepationObj == 'string' ? JSON.parse(insepationObj) : insepationObj;
				custFormData.value.beginTotalBudget = params.beginTotalBudget;
				custFormData.value.endTotalBudget = params.endTotalBudget;
				hyFormDefault.value.percentage = params.percentage;
				hyFormDefault.value.domain = params.domain;
				hyFormDefault.value.domainName = params.domainName;
				hyFormDefault.value.timeRange = [params.spotBeginTime, params.spotEndTime];
				searchDefault.value = params;
				searchFields.value.timeArr.remove = false;
				searchConfig.value.show = true;
				// console.log(params)
				nextTick(() => {
					tableConfig.value.request = spotList;
					hyTableRef.value.handleSearch();
				});
			}
		});
		return {
			tableColumns,
			tableConfig,
			searchFields,
			searchConfig,
			searchDefault,
			buttonConfig,
			dialogFormVisible,
			dialogFormOption,
			appCode,
			declareId,
			implementationId,
			hyFormOptionConfig,
			hyFormOptionFields,
			hyFormOptionDefault,
			hyFormFields,
			hyFormConfig,
			hyFormDefault,
			custFormData,
			hyDiaFormRef,
			hyTableRef,
			showDialogForm,
			closeDialog,
			confirm,
			handleCancel,
			fillOption,
			showDetail,
			setOptions,
			blurFirst,
		};
	},
});
</script>

<style scoped lang="scss">
.fillings-container {
	height: auto;
}

:deep(.el-input-number .el-input__inner) {
	text-align: left;
}
</style>
